package com.sl.happying.reading.controller;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileReader;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import com.sl.happying.reading.bean.Chapter;
import com.sl.happying.reading.bean.Novel;
import com.sl.happying.reading.service.NovelService;
import com.sl.happying.reading.util.FileUtil;

import io.swagger.annotations.ApiParam;

import org.apache.commons.lang3.StringUtils;
import org.junit.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.util.CollectionUtils;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

/**
 * 小说的处理类
 */
@Controller
@CrossOrigin
public class NovelController {

    @Autowired
    private NovelService novelService;

    /**
     * 保存小说
     *
     * @param file
     * @return
     * @throws Exception
     */
    @RequestMapping(value = "upload", method = RequestMethod.POST)
    @ResponseBody
    public String upload(@RequestParam("file") MultipartFile file) throws Exception {
        String fileName = file.getOriginalFilename();
        String context = new String(file.getBytes());
        if (StringUtils.isBlank(context)) {
            return null;
        }
        novelService.resolveNovel(context, fileName);
        return "success";
    }

    /**
     * 查询所有的小说
     *
     * @return
     */
    @RequestMapping(value = "findAll", method = RequestMethod.GET)
    @ResponseBody
    public List<Novel> findAllNovel() {
        return novelService.findAllNovel();
    }

    /**
     * 删除小说
     *
     * @param novelName
     * @return
     */
    @RequestMapping(value = "delete", method = RequestMethod.POST)
    @ResponseBody
    public List<Novel> delete(@ApiParam(value = "novelName", required = true) @RequestParam(value = "novelName", required = true) String novelName) {
        if (StringUtils.isBlank(novelName)) {
            return novelService.findAllNovel();
        }
        novelService.deleteNovel(novelName);
        return novelService.findAllNovel();
    }

    /**
     * 根据名称查询
     *
     * @param novelName
     * @return
     */
    @RequestMapping(value = "findByNovelName", method = RequestMethod.GET)
    @ResponseBody
    public List<Novel> findByNovelName(@ApiParam(value = "novelName", required = true) @RequestParam(value = "novelName", required = true) String novelName) {
        if (StringUtils.isBlank(novelName)) {
            return novelService.findAllNovel();
        }
        return novelService.findByNovelName(novelName);
    }
}
